<template>
    <el-dialog v-model="editData.visible" :title="editData.title" width="30%" top="10vh" :close-on-click-modal="false">
        <div class="edit-form">
            <el-form :model="editData.form" label-width="auto" style="width:100%" ref="formRef">
                <el-row :gutter="50">
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="上级目录">
                            <el-tree-select placeholder="请选择上级菜单" v-model="editData.form.parentId" :data="upLevelMenus" check-strictly :render-after-expand="false" show-checkbox default-expand-all style="width: 100%"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="目录名称" prop="name">
                            <el-input v-model="editData.form.name" placeholder="请输入目录名称"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="目录描述" prop="description">
                            <el-input type="textarea" v-model="editData.form.description" placeholder="请输入目录描述" rows="5"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="排序" prop="order_num">
                            <el-input-number v-model="editData.form.order_num" type="number" placeholder="请输入排序" :min="0"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="显示状态" prop="status">
                            <el-switch v-model="editData.form.status" :active-value="1" :inactive-value="0"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editData.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>


<script setup>
import { nextTick, reactive, ref, useTemplateRef } from 'vue'
import motionCatalogApi from 'api/model/motion-catalog.js'

const emits = defineEmits(['update'])
defineExpose({ openDialog })

// 编辑相关数据
const editData = reactive({
    type: 'add',
    visible: false,
    form: {
        id: null,
        parentId: '',
        name: null,
        description: '',
        order_num: '',
        status: 1
    }
})

// 项目表单ref 对象
const formRef = useTemplateRef('formRef')

const upLevelMenus = ref([
    { value: -1, label: '顶级菜单', children: [] }
])

/**
 * 打开弹框
 * @param type
 * @param item
 */
function openDialog (type, item) {
    editData.title = type === 'update' ? '编辑目录' : '新增目录'
    editData.visible = true
    editData.type = type
    editData.form.id = ''
    nextTick(() => {
        formRef.value.resetFields()
        if (type === 'add') {

            if (item && item.id) {
                editData.form.parentId = item.id || -1
                getList(item.id)
            } else {
                getList()
            }
        }
        if (type === 'update') {
            const { id, status, description, name, order_num, parentId } = item || {}
            editData.form.id = id
            editData.form.status = status
            editData.form.description = description
            editData.form.name = name
            editData.form.order_num = order_num
            editData.form.parentId = parentId ? Number(parentId) : -1
            getList(id)
        }
    })
}

/**
 * 提交表单
 */
function submitForm () {
    formRef.value.validate(async valid => {
        if (!valid) return
        editData.type === 'add' ? addItem() : updateItem()
    })
}

/**
 *  新增操作
 */
async function addItem () {
    const parentId = Array.isArray(editData.form.parentId) ? editData.form.parentId[0] : editData.form.parentId
    const { code, data = [] } = await motionCatalogApi.add.post({
        parentId,
        name: editData.form.name,
        description: editData.form.description,
        order_num: editData.form.order_num || 0,
        status: editData.form.status || 0
    })
    if (code === 200) {
        ElMessage.success('新增成功')
        editData.visible = false
        emits('update')
    }
}

/**
 *  更新操作
 */
async function updateItem () {
    const { code, data = [] } = await motionCatalogApi.update.post(editData.form)
    if (code === 200) {
        editData.visible = false
        ElMessage.success('编辑成功')
        emits('update')
    }
}

/**
 *  获取父级菜单列表
 */
async function getList () {
    const { code, data = [] } = await motionCatalogApi.tree.get()
    upLevelMenus.value[0].children = transformTree(data, editData.form.id)

}

function transformTree (data, excludeId = null) {
    return data
        .filter(item => item.id !== excludeId) // 先过滤掉当前节点（如果匹配 excludeId）
        .map(item => {
            const transformed = {
                value: item.id,
                label: item.name
            }

            // 如果有 children，递归处理（继承 excludeId）
            if (item.children && Array.isArray(item.children)) {
                transformed.children = transformTree(item.children, excludeId)
            }

            return transformed
        })
}


</script>

<style lang="less">

</style>
